package com.jetinno.utils;

import android.text.TextUtils;

import java.security.MessageDigest;


/**
 * Description :
 * Author :mhwang
 * Date : 2017/8/7
 * Version : V1.0
 */

public class Md5Util {


    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    public static String str2MD5(String str) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //将字符串转换成字符串数组
        char[] pswdArray = str.toCharArray();
        byte[] pswdByte = new byte[pswdArray.length];
        //将字符转换成字节
        for (int i = 0; i < pswdArray.length; i++) {
            pswdByte[i] = (byte) pswdArray[i];
        }
        byte[] digest = md5.digest(pswdByte);
        //将得到的字节数组转换成十六进制数
        StringBuffer buff = new StringBuffer();
        for (int i = 0; i < digest.length; i++) {
            int num = ((int) digest[i]) & 0xff;
            //如果不足16，加0填充
            if (num < 16)
                buff.append("0");
            buff.append(Integer.toHexString(num));
        }
        return buff.toString();
    }

    /** MD5加密
     * @param data 要加密的数据
     * @param encode 加密的编码
     * @return md5字符串
     */
    public static String str2MD5(String data, String encode) {
        String resultString = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (TextUtils.isEmpty(encode))
                resultString = byteArrayToHexString(md.digest(data.getBytes()));
            else {
                resultString = byteArrayToHexString(md.digest(data.getBytes(encode)));
            }
        } catch (Exception exception) {
        }
        return resultString;
    }

    /** byte数组转换16进制字符串
     * @param b 要转换的byte数组
     * @return 16进制字符串
     */
    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    /** byte转换成16进制字符串
     * @param b 要转换的byte
     * @return byte对应的16进制字符串
     */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

}
